//
//  SubjectsTableViewDataSource.m
//  LanguagesTeach
//
//  Created by Niel Santos on 12/16/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "SubjectsTableViewDataSource.h"
#import "MetaSubject.h"
#import "RowTableCell.h"

@implementation SubjectsTableViewDataSource


@synthesize subjectPath;


- (id)init: (SubjectPath*) localSubjectPath {
	
	NSString *fileDirectory;
	NSString *filePath;
	NSURL *url;
	NSXMLParser *xmlParser;
	BOOL success;
	
    if (self = [super init])
    {	
		subjectPath = localSubjectPath;
		fileDirectory = [NSString stringWithFormat:@"data/%@/%@/%@", 
						 [localSubjectPath languagePrefix],
						 [localSubjectPath levelFolder],
						 [localSubjectPath unitSubFolder]];
		filePath = [[NSBundle mainBundle] pathForResource:@"unit" ofType:@"xml" inDirectory: fileDirectory];
		url = [NSURL fileURLWithPath:filePath];
		
		
		xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
		xmlUnitParser = [[XMLUnitParser alloc] init];
		xmlParser.delegate = xmlUnitParser;
		success = [xmlParser parse];
		
		
		[xmlParser release];
		
		if(success){
			NSLog(@"No errors found");
		}else{
			NSLog(@"Warning a error was found");
		}
    }
    return self;	
}


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSMutableArray *metaSubjects;
	metaSubjects = [xmlUnitParser metaSubjects];
	return [metaSubjects count];
	
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSMutableArray *metaSubjects;
	MetaSubject *metaSubject;
	
    static NSString *CellIdentifier = @"Cell";
    
    RowTableCell *cell = (RowTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[RowTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		//accessory type
		cell.accessoryType= UITableViewCellAccessoryDetailDisclosureButton;			
    }
	
	metaSubjects = [xmlUnitParser metaSubjects];
	metaSubject = [metaSubjects objectAtIndex:indexPath.row]; 
	[cell.textLabel setText: [metaSubject title]];
	cell.prefix = metaSubject.folder;

	return cell;
}


- (void)dealloc {
	[xmlUnitParser release];
    [super dealloc];
}

@end
